import React, { Component } from 'react';
import { connect } from 'dva';

import { Form, Input, Button, notification, Col, Row, Modal, Cascader } from 'antd';
import { UmiComponentProps, FormComponentProps } from '@/common/type';

import TrimInput from '@/components/TrimInput'
import { DICT } from '../enum'
import { DropDownSelectObj } from '@/components/DropDownSelect';
import MapSelect from '@/components/MapSelect';

import { DividerItem } from '@/components/DividerItem';
import { fomatter } from '@/utils/formatter';

interface P {
  data?: {
    id?: string;
    valueRuleList: Array<any>;
    brandId?: string; productId?: string;
    brandName?: string; productName?: string;
    buildId?: string; floorId?: string; areaId?: string;
    buildName?: string; floorName?: string; areaName?: string;
    cameraSn: string;
  };
  user?: {
    companyName: string;
  }
  location?: Array<any>;
  brand?: Array<any>;
  dict?: any;
  fireList: Array<any>;
  image?: string;
  lBrand?: boolean;
}
type Props = P & UmiComponentProps & FormComponentProps;

@connect(({ device_camera, loading, user }) => ({
  dict: device_camera.dict || {},
  location: device_camera.location || [],
  brand: device_camera.brand || [],
  image: device_camera.image,
  lBrand: loading.effects['device_camera/queryBrand'],
  user: user.details || {},
  fireList: device_camera.fireroom || []
}))
class FormItem extends Component<Props, any> {
  state = {
    show: false,
    tmpLocation: null
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;

    dispatch({
      type: 'device_camera/init', payload: {
        dict: { keyList: DICT },
      }
    })
    if (data) {
      const {
        brandId, productId,
        buildId, floorId, areaId,
        buildName, floorName, areaName,
        brandName, productName,
        cameraSn = '',
        ...res
      } = data;

      form.setFieldsValue({
        cameraSn: cameraSn.split('://')[1],
        ...res,
        fire: '700190029',
      })
    } else {
      form.setFieldsValue({
        fire: '700190029',
      })
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { dispatch, form, data } = this.props;
    form.validateFields((err: undefined | {}, values: any) => {
      if (!err) {

        const res = FOMMATER.map(v => fomatter(
          values[v.list],
          data ? v.names.map(u => data[u]) : null,
          v.len,
          v.names
        ))

        const flag = FOMMATER.every(v => !!v);
        if (!flag) {
          notification['error']({
            message: `保存失败`,
            description: '信息录入不规范',
          });
          return;
        }

        let params = {
          cameraSn: `${values.cameraProtocol}://${values.cameraSn}`,
          ...values
        };

        res.forEach(v => {
          params = {
            ...v,
            ...params,
          }
        })
        delete params.systemNo

        data && data.id ? dispatch({
          type: 'device_camera/update',
          payload: {
            id: data.id,
            ...params
          },
        }) : dispatch({
          type: 'device_camera/create',
          payload: params
        })

      } else {
        notification['error']({
          message: `保存失败`,
          description: '信息录入不规范',
        });
      }
    })
  };

  loadData = (type, selectedOptions) => {

    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: `device_camera/${type}`,
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  render() {
    const { form, data, dict = {}, fireList } = this.props;
    const { getFieldDecorator, getFieldValue } = form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };

    const obj = {};
    Array.isArray(fireList) ? fireList.forEach(v => {
      obj[v.id] = v.name
    }) : []

    dict['camera.fireroom'] = obj

    const Info = DividerItem(data && data.id ? 'form' : 'plus', '监控摄像头')

    return (
      <Form onSubmit={this.handleSubmit}>
        <Info />
        <Row style={{ minHeight: '75vh' }}>
          <Col span={12}>
            {/* {
              data && data.id && <Form.Item
              {...formItemLayout}
              label="系统编号"
            >
              {getFieldDecorator('systemNo', {
                rules: [{
                  required: true, message: '请输入系统编号',
                }],
              })(
                <TrimInput placeholder='请输入系统编号' disabled/>
              )}
            </Form.Item>
            } */}
            <Form.Item
              {...formItemLayout}
              label='所属消控室'
            >
              {getFieldDecorator('fireRoomId', {
                rules: [{ required: true, message: '所属消控室' }],
              })(
                (DropDownSelectObj({ dict, type: 'camera.fireroom', onChange: () => { } }))
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="设备名称"
            >
              {getFieldDecorator('name', {
                rules: [{
                  required: true, message: '请输入设备名称',
                }],
              })(
                <TrimInput placeholder='请输入设备名称' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='检查类型'
            >
              {getFieldDecorator('fire', {
                rules: [{ required: true, message: '检查类型' }],
              })(
                (DropDownSelectObj({ dict, type: 'device.fire', disabled: true, onChange: () => { } }))
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="摄像头直播地址"
            >
              {getFieldDecorator('cameraLiveAddress', {
                rules: [{
                  required: true, message: '请输入直播地址',
                }],
              })(
                <TrimInput placeholder='请输入直播地址' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='摄像头协议'
            >
              {getFieldDecorator('cameraProtocol', {
                rules: [{ required: true, message: '摄像头协议' }],
              })(
                (DropDownSelectObj({ dict, type: 'camera.protocol',  onChange: () => { } }))
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="S/N码"
            >
              {getFieldDecorator('serialNumber')(
                <TrimInput placeholder='请输入S/N码' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='厂家型号'
              required
            >
              {getFieldDecorator('brandList')(
                <Cascader
                  options={this.props.brand}
                  loadData={this.loadData.bind(this, 'queryBrand')}
                  changeOnSelect={this.props.lBrand}
                  placeholder={data ? `${data.brandName}/${data.productName}` : '请选择'}
                />
              )}
            </Form.Item>

          </Col>
          <Col span={12}>

          </Col>
        </Row>
        <Button style={{ marginLeft: 20 }} onClick={() => {
          window.history.back()
        }}>取消</Button>
        <Button type="primary"
          htmlType="submit"
          style={{ marginLeft: 20 }}
        >保存</Button>
        <Modal
          visible={this.state.show}
          title="地图坐标"
          width={960}
          okText="保存"
          onCancel={() => this.setState({ show: false, tmpLocation: null })}
          onOk={() => {
            form.setFieldsValue({ location: this.state.tmpLocation ? this.state.tmpLocation.join(',') : '' })
            this.setState({ show: false, tmpLocation: null })
          }}
        >
          <MapSelect
            name={this.props.user.companyName || ''}
            location={getFieldValue('location') ? getFieldValue('location').split(',') : []}
            setPoint={v => this.setState({ tmpLocation: v })}
          />
        </Modal>
      </Form >
    );
  }
}

const FormList = Form.create<Props>()(FormItem);
export default FormList;

const FOMMATER = [{
  names: ['brandId', 'productId'],
  list: 'brandList',
  len: 2
}]
